package com.kfzx.www.imagetest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Base64Utils {

    /**
     * Created by 888 on 2017/11/20.
     */


    public static String Bitmap2Base64(Bitmap bitmap) {
        ByteArrayOutputStream BOS = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, BOS);
        byte[] bytes = BOS.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);


    }

    public static void Bitmap2Base64AndSaveFile(Bitmap bitmap, int number) {
        ByteArrayOutputStream BOS = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, number, BOS);
        byte[] bytes = BOS.toByteArray();

        String base64String =Base64.encodeToString(bytes,Base64.DEFAULT);



        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
        String fileName = dateFormat.format(date);
        File outputFile = new File(Environment.getExternalStorageDirectory(), fileName + ".txt");
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile));
            bufferedWriter.write(base64String);
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    public static Bitmap parseBase64(String stringSrc) {
        String substring = stringSrc.substring(22, stringSrc.length());
        byte[] decode = Base64.decode(substring, Base64.DEFAULT);
        Bitmap bt = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        return bt;
    }


}
